-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
46 lines (34 loc) · 966 Bytes
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <algorithm>
using namespace std;
// Binary Search function
int binarySearch(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
int main() {
int n, target;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the unsorted elements:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Enter the target element: ";
cin >> target;
sort(arr, arr + n); // Sort the array
int result = binarySearch(arr, n, target);
if (result != -1) {
cout << "Element found at index " << result << " (after sorting)." << endl;
} else {
cout << "Element not found." << endl;
}
return 0;
}